package com.atech.ebayadmin.system.filter;

import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;
import com.atech.ebayadmin.system.util.FilterUtil;
import com.atech.ebayadmin.system.vo.UserVO;


public class PermisionFilter extends OncePerRequestFilter{
	private static Logger log = LogManager.getLogger(PermisionFilter.class);
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
            log.info("用户请求的页面：" + request.getServletPath());
        String requesetUrl = request.getRequestURL().toString();
        String urlPath = request.getServletPath();
        String urlQurty = request.getQueryString();
    	if(urlPath.indexOf(".action") > 0){
    		urlPath = urlPath.substring(0,urlPath.indexOf(".action"));//如果有.action后缀，去掉.action后缀
    		log.info("去掉.action后缀后的URL为："+ urlPath);
    	}
//        System.out.println(requesetUrl);
//        System.out.println(urlPath);
//        System.out.println(urlQurty);
        //判断是否需要权限控制
        if(FilterUtil.getInstance().isNeedCheck(urlPath)){
            if (null != urlQurty) {
            	urlQurty = "?" + urlQurty;
            }
            else {
            	urlQurty = "";
            }
            urlQurty = URLEncoder.encode(request.getServletPath() + urlQurty, "GB2312");
            //需要权限控制，先判断用户是否登陆
            UserVO userVO = (UserVO)request.getSession().getAttribute("User");
            if(userVO != null){
            	//用户已经登陆
            	 log.info("用户已经登陆，登陆人为：" + userVO.getUserName());
            	if(FilterUtil.getInstance().isHasPermission(userVO.getRoleId(), urlPath)){
            		log.info("用户具有访问"+urlPath+"的权限");
                    filterChain.doFilter(request, response);
                    return;
            	}else{
            		log.error("用户不具有访问"+urlPath+"的权限");
                    request.setAttribute("errorMsg", "抱歉！" + "，您未获得授权访问该页面！");
                    request.getRequestDispatcher("/admin/loginError.jsp").forward(request, response);
            	}
            }else{
            	//用户未登陆
                log.info("用户未登陆或超时访问页面：" + request.getServletPath());
                request.setAttribute("errorMsg", "抱歉！您尚未登录，或登录已超时，请重新登录！");
                request.getRequestDispatcher("/admin/loginError.jsp").forward(request, response);
            }
            
        }else{
        	//不需要权限控制，直接跳过
            filterChain.doFilter(request, response);
            return;
        }
        response.setHeader("Connection", "close");
    }
}
